package com.xiaozhen.blog.controller.interceptor;


import com.alibaba.fastjson.JSON;
import com.xiaozhen.blog.entity.User;
import com.xiaozhen.blog.service.UserService;
import com.xiaozhen.blog.service.impl.LoginUser;
import com.xiaozhen.blog.utils.CookieUtil;
import com.xiaozhen.blog.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @create 2023-04-25 16:17
 * 拦截器
 */
@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisCache redisCache;

    // 在 Controller 之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 cookie 中获取凭证
        String token = CookieUtil.getValue(request, "token");
        if (token != null) {
            // 查询凭证
            LoginUser loginUser = userService.findLoginTicket(token);
            // 检查凭证是否有效
            // 如果凭证不为 null 并且 status == 0 （1 为过期） 并且 过期时间不超过当前时间
            if (loginUser != null) {
                // 根据凭证查询用户
                User user = userService.findUserById(loginUser.getUser().getId());
                // 在本次请求中持有用户
//                hostHolder.setUsers(user);
            }
        }
        return true;
    }

    // 在Controller 之后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 获取当前线程的用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String userId = authentication.getName();
        if (!"anonymousUser".equals(userId)) {
            String redisKey = "login:" + userId;
            LoginUser loginUser = JSON.parseObject(redisCache.getCacheObject(redisKey), LoginUser.class);
            System.out.println("获取到 redis 中的信息1：" + loginUser.getUser().toString());
            if (loginUser != null && modelAndView != null) {
                modelAndView.addObject("loginUser", loginUser.getUser());
            }
        }
    }

    // 在模板引擎 TemplateEngine 之后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        String userId = authentication.getName();
//        if (userId != "anonymousUser") {
//            String redisKey = "login:" + userId;
//            // 刷新redis缓存
//            // 这种方式适用于缓存的值是直接从数据库中获取的情况
//            redisCache.refreshCache(redisKey);
//            LoginUser loginUser = JSON.parseObject(redisCache.getCacheObject(redisKey), LoginUser.class);
//            System.out.println("获取到 redis 中的信息2：" + loginUser.getUser().toString());
//        }
    }
}
